<?php


namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\Admin;
use App\Models\NewRoles;
use App\Services\ModuleService;
use App\Services\StoreService;
use App\Services\UploadService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\URL;
use Illuminate\Support\Str;

class StoreController extends Controller
{
    private $request;

    private $storeService;

    private $uploadService;

    private const STORE_LEVEL = [
        1   => '级别一',
        2   => '级别二',
        3   => '级别三',
        4   => '级别四',
    ];

    public function __construct(Request $request, StoreService $storeService, UploadService $uploadService)
    {
        $this->request = $request;
        $this->storeService = $storeService;
        $this->uploadService = $uploadService;
    }

    public function index()
    {
        $page = [
            'page_name' => 'dealer',
            'title' => '门店信息',
        ];

        $model = DB::table('users as x')
            ->leftJoin('store_info as u', 'x.id', 'u.user_id')
            ->select(['x.abbr', 'x.first_name', 'x.phone_number', 'x.mdtype', 'x.id', 'u.front_show', 'u.is_advanced'])
            ->where('x.check_status',  '!=', 2);

        if (!is_null($this->request->input('front_show'))) {
            $model = $model->where('u.front_show', $this->request->input('front_show'));
        }

        if (!empty($this->request->input('mdtype'))) {
            $model = $model->where('x.mdtype', $this->request->input('mdtype'));
        }

        $model = filterByColumns($model, ['x.abbr','x.first_name','x.phone_number']);
        $data = $model->paginate(50);

        return view('admin.store.index',  [
            'data'=>$data,
            'page' => $page,
            'level' => self::STORE_LEVEL,
            'user_type' => $user_type ?? 0,
            'front_show' => $this->request->input('front_show') ?? '',
            'mdtype' => $this->request->input('mdtype') ?? 0,
        ]);
    }

    public function create()
    {
        $distributions = Admin::where(['status' => 1, 'user_type'=>2])->orderBy('unique_id')->get(['id', 'abbr', 'company_name']);
        $page = [
            'page_name' => 'warranty',
            'title' => '新增门店',
        ];
        return view('admin.store.create', [
            'page' => $page,
            'distributions' => $distributions,
            'data' => $data ?? [],
            'store_level' => self::STORE_LEVEL,
        ]);
    }

    public function uploadImage()
    {
        $file = $this->request->file('file');
        if (empty($file)) {
            return ['status'=>4001, 'name'=>'文件不存在'];
        }
        $ext = ["png", "jpg", "jpeg", "gif", "bmp"];
        $e = $file->getClientOriginalExtension();

        $pname = '/upload/'.date('Ym').'/';

        $basePath = public_path($pname);
        if (!file_exists($basePath)) {
            mkdir($basePath, 0755, true);
        }
        if (!in_array($e, $ext)) {
            return response()->json([
                'errno' => 1,
            ]);
        }
        $name = Str::random(30).'.'.$e;
        $file->storeAs($pname, $name);

        $data = [
            'errno' => 0,
            'data' => [
                [
                    'url' => 'http://' . $_SERVER["HTTP_HOST"] . $pname . $name,
                    'alt' => '图片',
                    'href' => '',
                ],
            ],
        ];

        return response()->json($data);
    }

    public function save()
    {
        $input = $this->request->input();
        if (empty($input)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少数据'
            ]);
        }
        try {
            $this->storeService->save($input);
        } catch (\Exception $e) {
            return response()->json([
                'code'  => $e->getCode() ?: 10000,
                'msg'   => $e->getMessage() ?: '保存失败'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success'
        ]);
    }

    public function edit(int $id)
    {
        $page = [
            'page_name' => 'dealer',
            'title' => '修改门店信息',
        ];

        $store = $this->storeService->getStoreInfo($id);
        $features = DB::table('store_features')->where('store_id', $store->store_id)->where('is_delete', 0)->where('type', 1)->get();
        $pictures = DB::table('store_features')->where('store_id', $store->store_id)->where('is_delete', 0)->where('type', 2)->get();

        $data = [
            'data' => $store,
            'id'    => $id,
            'page'  => $page,
            'features' => $features,
            'pictures' => $pictures,
            'store_level' => self::STORE_LEVEL,
        ];

        return view('admin.store.edit', $data);
    }

    public function update()
    {
        $input = $this->request->input();
        if (empty($input)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少数据'
            ]);
        }
        try {
            $this->storeService->update($input['id'], $input);
        } catch (\Exception $e) {
            return response()->json([
                'code'  => $e->getCode() ?: 10000,
                'msg'   => $e->getMessage() ?: '保存失败'
            ]);
        }

        return response()->json([
            'code'  => 0,
            'msg'   => 'success'
        ]);
    }

    public function delete($id)
    {
        $result = DB::table('store_info')->where('user_id', $id)->update(['is_delete' => 1]);
        if ($result) {
            return ['status' => 'SUCCESS', 'msg' => '成功！'];
        }

        return ['status' => false, 'msg' => '删除失败'];
    }

    public function deletes()
    {
        $ids = $this->request->input('ids');
        if (empty($ids)) {
            return response()->json([
                'code'  => 1000,
                'msg'   => '缺少数据'
            ]);
        }

        $count = 0;
        foreach ($ids as $k => $id) {
            $result = DB::table('store_info')->where('user_id', $id)->update(['is_delete' => 1]);
            if (!$result) {
                $count += 1;
            }
        }

        return ['status' => 'SUCCESS', 'msg' => $count . ' 条数据删除成功，'. (count($ids) - $count) .'条数据删除失败！'];
    }

    public function uploadVideo(Request $request)
    {
        $result = $this->uploadService->uploadVideo($request);

        $data = [
            'code' => 0,
            'data' => $result,
        ];

        return response()->json($data);
        $file = $this->request->file('file');
        if (empty($file)) {
            return ['status'=>4001, 'name'=>'文件不存在'];
        }
        $ext = ["mp4", "avi"];
        $e = $file->getClientOriginalExtension();
        $pname = '/upload/'.date('Ym').'/';

        $basePath = public_path($pname);
        if (!file_exists($basePath)) {
            mkdir($basePath, 0755, true);
        }
        if (!in_array($e, $ext)) {
            return response()->json([
                'errno' => 1,
            ]);
        }
        $name = Str::random(30).'.'.$e;
        $file->storeAs($pname, $name);

        $data = [
            'code' => 0,
            'data' => [
                'url' => 'http://' . $_SERVER["HTTP_HOST"] . $pname . $name,
                'alt' => '视频',
                'href' => '',
            ],
        ];

        return response()->json($data);
    }
}
